<?php

namespace App\Http\Controllers\Api;

use App\Models\Currency;
use App\Models\Entrust;
use App\Models\Property;
use App\Models\User;
use App\Models\Order;
use App\Models\CurrencyLog;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Exception;
use DB;
use App\Models\Message;
use App\Library\Orders\Orders;

/**
 * 货币管理.
 */
class CurrencyController extends Controller
{
    /**
     * 买卖页面显示.
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     *
     * @param  int    id    货币主键ID
     *
     * @return json
     */
    public function currency_market(Request $request)
    {
        $id = $request->get('cid');
        $type = $request->get('type');
        $uid = $request->get('uid');
        $pc = $request->get('pc');//PC专用
        if (empty($id) || empty($type))
            return respF(1000);
        $list = array();
        $order_model = new Orders();
        $currency_info = $order_model->currency_verify($id);
        if (!$currency_info)
            return respF(1000);
        //买入数据
        $where['cid'] = $id;
        $where['type'] = 3;
        $infos = Entrust::where($where)->whereIn('status', [1, 2])->orderBy('price', 'desc')
            ->take(5)->get(['price', 'deal', 'num']);
        //无数据时
        $arr = [
            '0' => ['price' => 0, 'y_num' => 0],
            '1' => ['price' => 0, 'y_num' => 0],
            '2' => ['price' => 0, 'y_num' => 0],
            '3' => ['price' => 0, 'y_num' => 0],
            '4' => ['price' => 0, 'y_num' => 0],
        ];
        $arr1 = [
            '0' => ['price' => 0, 'y_num' => 0],
            '1' => ['price' => 0, 'y_num' => 0],
            '2' => ['price' => 0, 'y_num' => 0],
            '3' => ['price' => 0, 'y_num' => 0],
            '4' => ['price' => 0, 'y_num' => 0],
        ];
        if (collect($infos)->count() < 1) {
            $list['buy'] = $arr;
        } else {
            foreach ($infos as $k => $v) {
                $list['buy'][$k]['price'] = number_format($v->price, 2,'.','');
                $list['buy'][$k]['y_num'] = number_format($v->num - $v->deal, 4,'.','');
            }
            switch (count($list['buy'])) {
                case 1:
                    unset($arr[0]);
                    $list['buy'] = array_merge($list['buy'], $arr);
                    break;
                case 2:
                    unset($arr[0]);
                    unset($arr[1]);
                    $list['buy'] = array_merge($list['buy'], $arr);
                    break;
                case 3:
                    unset($arr[0]);
                    unset($arr[1]);
                    unset($arr[2]);
                    $list['buy'] = array_merge($list['buy'], $arr);
                    break;
                case 4:
                    unset($arr[0]);
                    unset($arr[1]);
                    unset($arr[2]);
                    unset($arr[3]);
                    $list['buy'] = array_merge($list['buy'], $arr);
                    break;
                case 5:
                    break;
            }
        }
        //卖出数据
        $where1['cid'] = $id;
        $where1['type'] = 4;
        $infos3 = Entrust::where($where1)->whereIn('status', [1, 2])->orderBy('price', 'asc')
            ->take(5)->get(['price', 'deal', 'num']);
        if (collect($infos3)->count() < 1) {
            $list['sell'] = $arr1;
        } else {
            foreach ($infos3 as $k => $v) {
                $list['sell'][$k]['price'] = number_format($v->price, 2,'.','');
                $list['sell'][$k]['y_num'] = number_format($v->num - $v->deal, 4,'.','');
            }
            $list['sell'] = array_reverse($list['sell']);
            switch (count($list['sell'])) {
                case 1:
                    unset($arr1[0]);
                    $list['sell'] = array_merge($arr1,$list['sell']);
                    break;
                case 2:
                    unset($arr1[0]);
                    unset($arr1[1]);
                    $list['sell'] = array_merge($arr1,$list['sell']);
                    break;
                case 3:
                    unset($arr1[0]);
                    unset($arr1[1]);
                    unset($arr1[2]);
                    $list['sell'] = array_merge($arr1,$list['sell']);
                    break;
                case 4:
                    unset($arr1[0]);
                    unset($arr1[1]);
                    unset($arr1[2]);
                    unset($arr1[3]);
                    $list['sell'] = array_merge($arr1,$list['sell']);
                    break;
                case 5:
                    break;
            }
        }
        if (!empty($pc)){
            $list['sell'] = array_reverse( $list['sell']);
        }
        if ($type == 1) {
            $where5['cid'] = $order_model->get_standard();
        } else {
            $where5['cid'] = $id;
        }
        $list['buy_best'] = number_format($currency_info->official_price ?? 0,2,'.','');
        $infos1 = Entrust::where($where1)->whereIn('status',[1,2])->orderBy('price','asc')->first(['price']);
        if ($infos1)
            $list['buy_best'] = number_format($infos1->price,2,'.','');
        $list['sell_best'] = number_format($currency_info->official_price,2,'.','');
        $infos4 = Entrust::where($where)->whereIn('status',[1,2])->orderBy('price','desc')->first(['price']);
        if ($infos4)
            $list['sell_best'] = number_format($infos4->price,2,'.','');
        $currency_name_a = Currency::where('id', $where5['cid'])->first();
        if (!$currency_name_a) {
            return respF(1000);
        } else {
            $currency_name = $currency_name_a->name_en;
        }
        $currency_fee = Currency::where('id', $id)->first(['fee']);
        $data['is_currency'] = 0;
        if (!empty($uid)) {
            $where5['uid'] = $uid;
            $infos = Property::where($where5)->first(['balance', 'blocked', 'total']);
            if (empty($infos)) {
                $infos = [
                    'balance' => number_format(0, 8,'.',''),
                    'blocked' => number_format(0, 8,'.',''),
                    'total' => number_format(0, 8,'.',''),
                ];
            }
            $where6['cid'] = $id;
            $where6['uid'] = $uid;
            $is_currency_info = Property::where($where6)->first();
            if ($is_currency_info)
                $data['is_currency'] = 1;
        } else {
            $infos = [
                'balance' => '-',
                'blocked' => '-',
                'total' => '-',
            ];
        }
        if ($currency_info->is_standard == 2) {
            $oba = 1;
        } else {
            $oba = 0;
        }
        $data['list']           = $list;
        $data['infos']          = $infos;
        $data['currency_name']  = $currency_name;
        $data['currency_fee']   = $currency_fee->fee;
        $data['oba']            = $oba;
        $data['unit']           =  $currency_info->unit;
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 持有货币行情.
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/5/15
     *
     * @param  int    uid    用户ID
     *
     * @return json
     */
    public function user_currency_market(Request $request)
    {
        $uid = $request->get('uid');
        $where['uid'] = $uid;
        $property = Property::where($where)->where('total', '>', 0)->get(['cid', 'uid', 'total', 'balance']);
        $order_model = new Orders();
        $usd_id = $order_model->get_standard();
        if (collect($property)->count() > 0) {
            $list = array();
            foreach ($property as $k => $v) {
                if ($v->cid == $usd_id){
                    unset($list[$k]);
                }else{
                    $currency = $v->currency;
                    $list[$k]['name_en'] = $currency->name_en;
                    $list[$k]['cid'] = $v->cid;
                    $list[$k]['total'] = $v->total;
                    $list[$k]['balance'] = $v->balance;
                    $price = Order::where('cid', $v->cid)->orderBy('id', 'desc')->first();
                    if ($price) {
                        $list[$k]['price'] = $price->price;
                    } else {
                        $list[$k]['price'] = $currency->official_price;
                    }
                    $c_log_model = new CurrencyLog();
                    $pan = $c_log_model->get_last_close_price($v->cid);
                    $volatility = sprintf("%.2f",bcmul(bcdiv(bcsub($list[$k]['price'], $pan, 4), $pan, 4), 100, 4));
                    if ($volatility>0){
                        $list[$k]['volatility'] = '+'.$volatility;
                    }elseif ($volatility<0){
                        $list[$k]['volatility'] = $volatility;
                    }else{
                        $list[$k]['volatility'] = '0.00';
                    }
                }
            }
            if (count($list)<1){
                return respF(1009);
            }
            return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => array_values($list)]);
        } else {
            return respF(1009);
        }
    }

    /**
     * 可买数量.
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/5/16
     *
     * @param  int    cid    币种ID
     *
     * @return json 可买数量返回值
     */
    public function trading_num(Request $request)
    {
        $cid = $request->get('cid');
        $price = $request->get('price');
        $type = $request->get('type');
        if (empty($cid) || empty($price) || empty($type))
            return respF(1003);
        $order_model = new Orders();
        $currency = $order_model->currency_verify($cid);
        if (!$currency)
            return respF(1000);
        $where['cid'] = $cid;
        switch($type){
            case 1:
                $where['type'] = 4;
                $all_num = Entrust::where($where)
                    ->Where('price', '<=', (float) $price)
                    ->whereIn('status', [1, 2])
                    ->sum('num');
                $c_num = Entrust::where($where)
                    ->Where('price', '<=', (float) $price)
                    ->whereIn('status', [1, 2])
                    ->sum('deal');
                break;
            case 2:
                $where['type'] = 3;
                $all_num = Entrust::where($where)
                    ->Where('price', '>=', (float) $price)
                    ->whereIn('status', [1, 2])
                    ->sum('num');
                $c_num = Entrust::where($where)
                    ->Where('price', '>=', (float) $price)
                    ->whereIn('status', [1, 2])
                    ->sum('deal');
                break;
            default:
                return respF(1003);
        }
        $unit = $currency->unit;
        $num = bcsub($all_num,$c_num,$unit);
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $num]);
    }

    /**
     * 货币列表.
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     *
     * @return json 货币列表集合
     */
    public function currency_list(Request $request)
    {
        $where['online_switch'] = 1;
        $where['pay_switch'] = 1;
        $where['buy_switch'] = 1;
        $data = Currency::where($where)->where('is_standard', '!=', 1)
            ->orderBy('orderby', 'asc')->get(['id', 'logo', 'name', 'name_en', 'orderby']);
        if (collect($data)->count() == 0)
            return respF(1009);
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 支持转入转出的货币列表.
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/5/17
     *
     * @return json 货币列表集合
     */
    public function currency_turn_list(Request $request)
    {
        $where['online_switch'] = 1;
        $where['pay_switch'] = 1;
        $where['buy_switch'] = 1;
        $data = Currency::where($where)
            ->where('is_standard', '!=', 1)
            ->whereIn('name_en', config('config.roll'))
            ->orderBy('orderby', 'asc')->get(['id', 'logo', 'name', 'name_en', 'orderby']);
        if (collect($data)->count() == 0)
            return respF(1009);
        $data = $data->toArray();
        foreach ($data as $k =>$v){
            $data[$k]['logo'] = config('alioss.host').'/'.$v['logo'];
        }
        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $data]);
    }

    /**
     * 资产管理.
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/14
     *
     * @param  int    uid    用户ID
     *
     * @return json 资产列表
     */
//    public function property_list(Request $request)
//    {
//        $info = $request->all();
//        if (empty($info['uid']))
//            return respF(1004);
//        $where['uid'] = $info['uid'];
//        $order_model = new Orders();
//        $ids = $order_model->currency_id();
//        $infos = Property::whereIn('cid',$ids)->where($where)->get(['balance', 'blocked', 'total']);
//        if (empty($infos))
//            return respF(1005);
//        return response()->json(['status' => 1, 'msg' => '查询成功', 'data' => $infos]);
//    }

    /**
     * 生成委托单.
     *
     * @ author: zrc
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/13
     *
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     *
     * @return void|int|string|bool|array comment
     */
    public function entrust_create(Request $request)
    {
        $order_model = new Orders();
        $info = $request->all();
        if (empty($info['type']) || empty($info['uid']) || empty($info['price']) || empty($info['num']) || empty($info['cid']))
            return respF(1000);
        if((float) $info['num'] < 0.00000001 ||(float) $info['price'] < 0.00000001)
            return respF(1000);
        if ((float) $info['num'] > 1000000 || (float) $info['price'] > 100000 || (float) ($info['price'] * $info['num']) > 100000000000)
            return respF(1041);
        //验证密码
        $user_info1 = User::where('id', $info['uid'])->first();
        if ($user_info1->real_status != 2)
            return respF(2005);
        $c_info = $order_model->currency_verify($info['cid']); //验证货币信息
        if ($c_info->is_standard == 2 && (float) $info['num'] > $c_info->total)
            return respF(1041);
        $data = array();
        $where['uid'] = $info['uid'];
        $s_p = bcmul(bcmul($info['num'], $info['price'], 8), $c_info->fee / 100, 8);
        if ($info['type'] == 1) {//买入委托单
            $where['cid'] = $order_model->get_standard();
            $data['type'] = 3;
            //买家冻结手续费用加上买入所需要的钱
            $p_num = bcmul($info['num'], $info['price'], 8) + $s_p;
        } elseif ($info['type'] == 2) {//卖出委托单
            $where['cid'] = $info['cid'];
            $data['type'] = 4;
            $p_num = (float) $info['num'];
        } else {
            return respF(1000);
        }
        //查询资产
        $user_property = $order_model->property_verif($where['uid'], $where['cid']);
        if ($user_property->balance < (float) $p_num)
            return respF(1036);
        //组装数据
        $data['uid'] = $info['uid'];
        $data['cid'] = $info['cid'];
        $data['number_no'] = get_microtimes('WTD');
        $data['price'] = $info['price'];
        $data['num'] = $info['num'];
        $data['status'] = 1;
        $data['deal'] = 0;
        $data['proc'] = $s_p;
        //更改资产数据
        try {
            //开启事务
            DB::beginTransaction();
            $e_id = Entrust::insertGetId($data);
            $user_property->increment('blocked', $p_num);
            $user_property->decrement('balance', $p_num);
            $re = $this->pair_deal($e_id);
            if ($re != true)
                throw new Exception(1018);
            DB::commit();
            return response()->json(['status' => 1, 'msg' => '提交成功']);
        } catch (Exception $e) {
            DB::rollback();
            $msg = $e->getMessage();//接收错误号
            return respF($msg);
        }
    }

    /**
     * 匹配订单
     *
     * @ author: ZUORENCI
     * @ E-mail:904725327@qq.com
     * @ date: 2018/3/23
     * @access public
     * @param  mixed    name    comment
     * @param  int    name    comment
     * @param  string    name    comment
     * @param  bool       name    comment
     * @param  array   name    comment
     * @return void|int|string|boolean|array        comment
     */
    public function pair_deal($id)
    {
        $order_model = new Orders();
        if (empty($id))
            return false;
        $list = Entrust::where('id',$id)->first();
        if (!$list)
            return false;
        $c_info = $order_model->currency_verify($list->cid);//交易货币的信息
        $b_c_id = $order_model->get_standard();
        $where_p['cid'] = $list->cid;
        $msg_model = new Message();
        if ($list->type==3) {  //买入
            $where_p['type'] = 4;
            $list_a = Entrust::where($where_p)->where('price','<=',(float)$list->price)->whereIn('status',[1,2])->first();
            if ($list_a) {
                do{
                    //匹配卖的订单
                    $info_a = Entrust::where($where_p)->where('price','<=',(float)$list->price)->whereIn('status',[1,2])->orderBy('price','asc')->first();//卖的数据
                    $info_b = Entrust::where('id',$id)->whereIn('status',[1,2])->first();//买家数据
                    if ($info_a &&$info_b){
                        $num1 = $info_a->num - $info_a->deal;//卖订单剩余量
                        $num2 = $info_b->num - $info_b->deal;//买订单剩余量
                        if ($num1<=$num2){
                            $num3 = $num1;//当前交易数量
                        }else{
                            $num3 = $num2;//当前交易数量
                        }
                        if (!$num3)
                            return true;
                        //修改卖方委托单数据
                        $data1['deal'] = $num3+$info_a->deal;
                        $data1['deal_time'] = time();
                        if ($info_a->num == $data1['deal']){
                            $data1['status'] =3;//订单完成
                        }else{
                            $data1['status'] =2;
                        }
                        //修改买方委托单数据
                        $data2['deal'] = $num3+$info_b->deal;
                        $data2['deal_time'] = time();
                        if ($data2['deal']==$info_b->num){
                            $data2['status'] = 3;
                        }else{
                            $data2['status'] = 2;
                        }
                        //修改资产数据
                        //卖方 扣除卖出的货币  得到本位币（价格x数量-手续费）
                        $s_proc = $num3*$info_a->price*($c_info->fee)/100;//卖方手续费
                        $u_proc = ($info_a->price)*($c_info->fee)*$num3/100;//买方扣除USDT手续费
                        $uu_proc = ($info_b->price)*($c_info->fee)*$num3/100;//买方已冻结USDT手续费
                        //卖方资产信息变更
                        //交易币减少  扣除冻结的
                        $where_s1['uid'] = $info_a->uid;
                        $where_s1['cid'] = $info_a->cid;
                        $money_s1 = $num3;
                        //本位币增加
                        $where_s2['uid'] = $info_a->uid;
                        $where_s2['cid'] = $b_c_id;
                        $money_s2 = bcmul($info_a->price, $num3, 8)-$s_proc;
                        //买方资产信息变更
                        //交易币增加
                        $where_u1['uid'] = $info_b->uid;
                        $where_u1['cid'] = $info_b->cid;
                        $money_u1 = $num3;
                        //本位币减少
                        $where_u2['uid'] = $info_b->uid;
                        $where_u2['cid'] = $b_c_id;
                        $money_u2 = bcmul($info_a->price, $num3, 8)+$u_proc;
                        //买方
                        try {

                            //开启事务
                            DB::beginTransaction();
                            //检查用户资产信息
                            $user_p = $order_model->check_balance($info_b->uid,$info_b->cid);
                            if (!$user_p)
                                return FALSE;

                            //卖的委托单信息更改
                            $info_a->update($data1);

                            //买的委托单信息更改
                            $info_b->update($data2);
                            //var_dump($where_s1);
                            //var_dump($money_s1);
                            //$b = Property::where($where_s1)->first()->toArray();


                            Property::where($where_s1)->decrement('blocked',$money_s1);
                            Property::where($where_s1)->decrement('total',$money_s1);
                            Property::where($where_s2)->increment('balance',$money_s2);
                            Property::where($where_s2)->increment('total',$money_s2);

                            Property::where($where_u1)->increment('balance',$money_u1);
                            Property::where($where_u1)->increment('total',$money_u1);

                            if ((float)$list->price>(float)$info_a->price){
                                $money_cj = bcmul($list->price-$info_a->price, $num3, 8)-$u_proc+$uu_proc;
                                Property::where($where_u2)->decrement('blocked',$money_u2+$money_cj);
                                Property::where($where_u2)->increment('balance',$money_cj);
                                Property::where($where_u2)->decrement('total',$money_u2);
                            }else{
                                Property::where($where_u2)->decrement('blocked',$money_u2);
                                Property::where($where_u2)->decrement('total',$money_u2);
                            }
                            //生成资产记录和订单信息

                            $re = $order_model->place_order($id,$info_a->id,$info_b->uid,$info_a->uid,$info_a->cid,$info_a->price,$num3,$u_proc,$s_proc,$info_b->number_no,$info_a->number_no);
                            if ($re!=true)
                                return false;
                            DB::commit();
                            //生成通知消息
                            if ($num3==$list->num){
                                $msg = [
                                    'msg_id'=>5,
                                    'uid'=>$info_b->uid,
                                    'message'=>[
                                        date('Y-m-d H:i:s', $data2['deal_time']),//时间
                                        $c_info->name_en,//货币名称
                                        $list->num,//委托数量price
                                        $list->price,//委托单价
                                        $num3//成交数量
                                    ],
                                    'push_message'=>[
                                        $c_info->name_en//货币名称
                                    ],
                                    'title'=>[
                                        $c_info->name_en
                                    ]
                                ]; //全部成交
                            }else{
                                $msg = [
                                    'msg_id'=>7,
                                    'uid'=>$info_b->uid,
                                    'message'=>[
                                        date('Y-m-d H:i:s', $data2['deal_time']),//时间
                                        $c_info->name_en,//货币名称
                                        $list->num,//委托数量price
                                        $list->price,//委托单价
                                        $num3,//成交数量
                                        $info_a->price//成交单价
                                    ],
                                    'push_message'=>[
                                        $c_info->name_en//货币名称
                                    ],
                                    'title'=>[
                                        $c_info->name_en
                                    ]
                                ]; //全部成交
                            }

                            if ($num3==$info_a->num){
                                $msg1 = [
                                    'msg_id'=>6,
                                    'uid'=>$info_a->uid,
                                    'message'=>[
                                        date('Y-m-d H:i:s', $data2['deal_time']),//时间
                                        $c_info->name_en,//货币名称
                                        $list->num,//委托数量price
                                        $list->price,//委托单价
                                        $num3//成交数量
                                    ],
                                    'push_message'=>[
                                        $c_info->name_en//货币名称
                                    ],
                                    'title'=>[
                                        $c_info->name_en
                                    ]
                                ]; //全部成交
                            }else{
                                $msg1 = [
                                    'msg_id'=>8,
                                    'uid'=>$info_a->uid,
                                    'message'=>[
                                        date('Y-m-d H:i:s', $data2['deal_time']),//时间
                                        $c_info->name_en,//货币名称
                                        $list->num,//委托数量price
                                        $list->price,//委托单价
                                        $num3,//成交数量
                                        $info_a->price//成交单价
                                    ],
                                    'push_message'=>[
                                        $c_info->name_en//货币名称
                                    ],
                                    'title'=>[
                                        $c_info->name_en
                                    ]
                                ]; //全部成交
                            }
                            $msg_model->syspublishsmsAll($msg);
                            $msg_model->syspublishsmsAll($msg1);
                        } catch (Exception $e) {
                            DB::rollback();
                            return false;
                        }
                    }
                }while(Entrust::where('id',$id)->first()->status==2&&(!empty(Entrust::where($where_p)->where('price','<=',(float)$list->price)->whereIn('status',[1,2])->first())));
            }
            return true;
        } else {//卖委托单   匹配买
            $where_p['type'] = 3;
            $list_a = Entrust::where($where_p)->where('price','>=',(float)$list->price)->whereIn('status',[1,2])->first();

            if ($list_a) {
                do{
                    //匹配买的订单
                    $info_a = Entrust::where('id',$id)->whereIn('status',[1,2])->first();//卖家数据
                    $info_b = Entrust::where($where_p)->where('price','>=',(float)$list->price)->whereIn('status',[1,2])->orderBy('price','desc')->first();//买的数据
                    if ($info_a &&$info_b){
                        $num1 = $info_a->num - $info_a->deal;
                        $num2 = $info_b->num - $info_b->deal;
                        if ($num1<=$num2){
                            $num3 = $num1;
                        }else{
                            $num3 = $num2;
                        }
                        if (!$num3)
                            return true;
                        //修改卖方委托单数据
                        $data1['deal'] = $num3+$info_a->deal;
                        $data1['deal_time'] = time();

                        if ($info_a->num == $data1['deal']){
                            $data1['status'] =3;
                        }else{
                            $data1['status'] =2;
                        }
                        //修改买方委托单数据
                        $data2['deal'] = $num3+$info_b->deal;
                        $data2['deal_time'] = time();

                        if ($data2['deal']==$info_b->num){
                            $data2['status'] = 3;
                        }else{
                            $data2['status'] = 2;
                        }
                        //修改资产数据
                        //卖方 扣除卖出的货币  得到本位币（价格x数量-手续费）
                        $s_proc = $num3*$info_b->price*($c_info->fee)/100;//卖方扣除得到本位币的手续费
                        $u_proc = $info_b->price*$c_info->fee*$num3/100;//买房扣除交易货币的手续费
                        //卖方资产信息变更
                        //交易币减少  扣除冻结的
                        $where_s1['uid'] = $info_a->uid;
                        $where_s1['cid'] = $info_a->cid;
                        $money_s1 = $num3;
                        //本位币增加
                        $where_s2['uid'] = $info_a->uid;
                        $where_s2['cid'] = $b_c_id;
                        $money_s2 = $info_b->price*$num3-$s_proc;
                        //买方资产信息变更
                        //交易币增加
                        $where_u1['uid'] = $info_b->uid;
                        $where_u1['cid'] = $info_b->cid;
                        $money_u1 = $num3;
                        //本位币减少
                        $where_u2['uid'] = $info_b->uid;
                        $where_u2['cid'] = $b_c_id;
                        $money_u2 = $info_b->price*$num3+$u_proc;

                        //买方
                        try {
                            //开启事务
                            DB::beginTransaction();
                            //检查用户资产信息
                            $user_p = $order_model->check_balance($info_b->uid,$info_b->cid);
                            if (!$user_p)
                                return false;
                            //卖的委托单信息更改
                            $info_a->update($data1);
                            //买的委托单信息更改
                            $info_b->update($data2);
                            Property::where($where_s2)->increment('balance',$money_s2);
                            Property::where($where_s2)->increment('total',$money_s2);
                            Property::where($where_u2)->decrement('blocked',$money_u2);
                            Property::where($where_u2)->decrement('total',$money_u2);
                            Property::where($where_u1)->increment('balance',$money_u1);
                            Property::where($where_u1)->increment('total',$money_u1);
                            Property::where($where_s1)->decrement('blocked',$money_s1);
                            Property::where($where_s1)->decrement('total',$money_s1);


                            //生成资产记录和订单信息
                            $re = $order_model->place_order($id,$info_b->id,$info_b->uid,$info_a->uid,$info_a->cid,$info_b->price,$num3,$u_proc,$s_proc,$info_b->number_no,$info_a->number_no);
                            if ($re!=true)
                                return false;
                            DB::commit();
                            //生成通知消息
                            if ($num3==$info_a->num){
                                $msg = [
                                    'msg_id'=>6,
                                    'uid'=>$info_a->uid,
                                    'message'=>[
                                        date('Y-m-d H:i:s', $data1['deal_time']),//时间
                                        $c_info->name_en,//货币名称
                                        $info_b->num,//委托数量price
                                        $info_b->price,//委托单价
                                        $num3//成交数量
                                    ],
                                    'push_message'=>[
                                        $c_info->name_en//货币名称
                                    ],
                                    'title'=>[
                                        $c_info->name_en
                                    ]
                                ]; //全部成交
                            }else{
                                $msg = [
                                    'msg_id'=>8,
                                    'uid'=>$info_a->uid,
                                    'message'=>[
                                        date('Y-m-d H:i:s', $data1['deal_time']),//时间
                                        $c_info->name_en,//货币名称
                                        $info_b->num,//委托数量price
                                        $info_b->price,//委托单价
                                        $num3,//成交数量
                                        $info_b->price//成交单价
                                    ],
                                    'push_message'=>[
                                        $c_info->name_en//货币名称
                                    ],
                                    'title'=>[
                                        $c_info->name_en
                                    ]
                                ]; //全部成交
                            }


                            if ($num3==$info_b->num){
                                $msg1 = [
                                    'msg_id'=>5,
                                    'uid'=>$info_b->uid,
                                    'message'=>[
                                        date('Y-m-d H:i:s', $data2['deal_time']),//时间
                                        $c_info->name_en,//货币名称
                                        $info_b->num,//委托数量price
                                        $info_b->price,//委托单价
                                        $num3//成交数量
                                    ],
                                    'push_message'=>[
                                        $c_info->name_en//货币名称
                                    ],
                                    'title'=>[
                                        $c_info->name_en
                                    ]
                                ]; //全部成交
                            }else{
                                $msg1 = [
                                    'msg_id'=>7,
                                    'uid'=>$info_b->uid,
                                    'message'=>[
                                        date('Y-m-d H:i:s', $data2['deal_time']),//时间
                                        $c_info->name_en,//货币名称
                                        $info_b->num,//委托数量price
                                        $info_b->price,//委托单价
                                        $num3,//成交数量
                                        $info_a->price//成交单价
                                    ],
                                    'push_message'=>[
                                        $c_info->name_en//货币名称
                                    ],
                                    'title'=>[
                                        $c_info->name_en
                                    ]
                                ]; //全部成交
                            }
                            $msg_model->syspublishsmsAll($msg);
                            $msg_model->syspublishsmsAll($msg1);
                        } catch (Exception $e) {
                            DB::rollback();
                            return false;
                        }
                    }
                }while(Entrust::where('id',$id)->first()->status==2&&(!empty(Entrust::where($where_p)->where('price','>=',(float)$list->price)->whereIn('status',[1,2])->first())));
            }
            return true;
        }
    }

    public function test(Request $request)
    {
        $a = Currency::find(1)->order()->get()->toArray();
//        foreach ($a as $v){
//            dump($v);
//        }
        dump($a);
        die;
        $info = $request->all();
        dump($info);
        $order_model = new Orders();
        $a = $order_model->s_e($info['id']);
        dump($a);
        die;
        $card = '42092119920507x';
        $l = strlen($card);
        $b = substr($card, -4);
        if ($l == 15) {
            $c = substr($card, 0, -9);
            $t = '*****';
        } else {
            $t = '********';
            $c = substr($card, 0, -12);
        }

        dump($c.$t.$b);
        die;
        $str = '欧阳志';
        $a = splitName($str);
        $str1 = $a[0];
        $num = mb_strlen($a[1]);
        dump($num);
        if ($num == 1) {
            $str2 = '*';
        } elseif ($num == 2) {
            $str2 = '**';
        } else {
            $str2 = '***';
        }
        $name = $str1.$str2;
        dump($name);
        die;
        $info = $request->all();
        $order = Entrust::first();
        $aa = strval($order->id);
        //var_dump($aa);die;

        $a = bcmul(1, $info['price'], 2);
        var_dump($a);
        die;
        $a = collect($order_model->currency_verify($order_model->get_standard()));
        dump($a);
        die;
        $list = Currency::first()->toArray();
        dump($list);
        die;
        $orders_function = new Orders();
        $a = $orders_function->place_order(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
        //$a = $order_model->pair_deal();
        dump($a);
    }
}
